<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Token;
use app\common\model\card\Type;
use app\common\model\Member;
use app\common\model\Merchant;
use app\common\model\Merchantgoods;
use app\common\model\Merchantpost;
use app\common\model\Merchantuser;
use app\common\model\Merchantvisit;
use app\common\model\Mycard;
use app\common\model\Mycardlog;
use app\common\model\Order;
use app\common\model\Washlog;
use app\common\model\Write;
use Exception;
use fast\Random;
use think\Db;
use think\Validate;

/**
 * 店铺接口
 */
class Shop extends Api
{
    protected $noNeedLogin = ['merchantLogin','merchantRego','cardType','text'];
    protected $noNeedRight = ['*'];
    protected $merchantUser = [];
    protected $merchant = [];

    public function text(){

        $mycardModel = new Mycard();
        $mycardModel->getCode(	24, 0);//生成二维码
    }
    public function _initialize()
    {
        parent::_initialize();
        if (!$this->auth->match($this->noNeedLogin)) {
            /*判断当前账号身份 start*/
            $token = $this->request->server('HTTP_TOKEN', $this->request->request('token', \think\Cookie::get('token')));
            $token=Token::get($token);
            if($token["type"]!=1) $this->error("身份错误");//1 店铺 2区域服务商 3卡经销商 4分销商 0普通用户
            /*判断当前账号身份 end*/
            $user = Merchantuser::get($this->auth->id);
            $merchant=Merchant::where(["id"=>$user["merchant_id"]])->find();
            if(empty($merchant)) $this->error("店铺不存在");
            if(empty($merchant["status"])) $this->error("店铺审核中");
            if($merchant["status"]==2) $this->error("店铺已被驳回：".$merchant["remark"]);
            if($merchant["status"]==3) $this->error("店铺已被禁用");
            $this->merchantUser=$user;
            $this->merchant=$merchant;
        }
    }

    /**
     * 修改店铺资料
     * */
    public function merchantUpdate(){
        $data=[
            ['name', 'require', '店铺名称不能为空'],
            ['logo', 'require', '店铺logo不能为空'],
            ['address', 'require', '店铺地址不能为空'],
            ['classify', 'require', '店铺地址不能为空'],
            ['door_image', 'require', '门头照片不能为空'],
            ['license_image', 'require', '营业执照不能为空'],
            ['door_contacts', 'require', '店铺联系人不能为空'],
            ['telephone', 'require', '店铺联系号码不能为空'],
        ];
        $validate = new \think\Validate($data);
        if (!$validate->check(input())) {
            $this->error('提交失败：' . $validate->getError());
        }
        $params = $this->request->param();
        $merchant=Merchant::get($this->merchantUser["merchant_id"]);
        if(empty($merchant)) $this->error("店铺不存在");
        $ret=false;
        Db::startTrans();
        try {
            $ret=$merchant->allowField(true)->save($params);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($ret) {
            $this->success(__('修改成功'));
        } else {
            $this->error("修改失败");
        }
    }


    /**
     * 营业状态修改
     * */
    public function openSwitch(){
        $merchant=Merchant::find($this->merchantUser["merchant_id"]);
        $openswitch = $this->request->post('openswitch')??0;
        $merchant->save(["openswitch"=>$openswitch]);
        $this->success("成功");
    }

    /**
     * 检查店铺状态
     * */
    /*protected function checkShop($type=0){
        $token = $this->request->server('HTTP_TOKEN', $this->request->request('token', \think\Cookie::get('token')));
        $token=Token::get($token);
        if($token["type"]!=1) $this->error("身份错误");//1 店铺 2区域服务商 3卡经销商 4分销商 0普通用户
        $user = Merchantuser::get($this->auth->id);
        $merchant=Merchant::find($user["merchant_id"]);
        if(empty($merchant)) $this->error("店铺不存在");
        if($merchant["status"]!=1)$this->error("店铺状态错误");
        return $user;
    }*/

    /**
     * 营业时间修改
     * */
    public function openTime(){
        $data=[
            ['start_time', 'require', '营业开始时间不能为空'],
            ['end_time', 'require', '营业结束时间不能为空'],
        ];
        $validate = new \think\Validate($data);
        if (!$validate->check(input())) {
            $this->error('提交失败：' . $validate->getError());
        }
        $param = $this->request->param();
        $merchant=Merchant::find($this->merchantUser["merchant_id"]);
        $merchant->save([
            "start_time"=>$param["start_time"],
            "end_time"=>$param["end_time"],
        ]);
        $this->success("成功");
    }

    /******************************** 店铺商品管理 start*****************************************************************************/


    /**
     * 商品列表
     * */
    public function listGoods(){
        $page = !$this->request->param('page') ? 1 : $this->request->param('page');//页
        $where=["merchant_id"=>$this->merchantUser["merchant_id"],"card_type_id"=>0];
        $param=$this->request->param();
        if(isset( $param["type_data"]) && $param["type_data"]!=2){
            $where["type_data"]=$this->request->param('type_data');
        }
        $list=Merchantgoods::field("id,name,price,refer,images,status,type_data,cost_price,number,start_time,end_time")
            ->where($where)
            ->order("createtime","desc")
            ->paginate(10, '', ['page' => $page, 'list_rows' => 10])
            ->each(function ($v){
                if(!empty($v["images"])) $v["images"]=explode(",",$v["images"]);
                if(!empty($v["start_time"])) $v["start_time"]=date("Y-m-d H:i:s",$v["start_time"]);
                if(!empty($v["end_time"])) $v["end_time"]=date("Y-m-d H:i:s",$v["end_time"]);
            });
        $this->success("成功",$list);
    }


    /**
     * 新增商品
     * */
    public function addGoods(){
        $data=[
            ['name', 'require', '名称不能为空'],
            ['price', 'require', '价格不能为空'],
            ['type_data', 'require', '类型不能为空'],
        ];
        if($this->request->param("type_data")==1){
            //次卡
            $data=array_merge($data,[
                ['cost_price', 'require', '原价不能为空'],
                ['number', 'require', '次数不能为空'],
                ['start_time', 'require', '开始时间不能为空'],
                ['end_time', 'require', '结束时间不能为空'],
            ]);
        }
        $validate = new \think\Validate($data);
        if (!$validate->check(input())) {
            $this->error('提交失败：' . $validate->getError());
        }
        $params = $this->request->param();
        $params["merchant_id"]=$this->merchantUser["merchant_id"];
        $model=new Merchantgoods();
        if($params["type_data"]==1){
            $params["start_time"]=strtotime($params["start_time"]);
            $params["end_time"]=strtotime($params["end_time"]);
        }
        $model->allowField(true)->save($params);
        $this->success("成功");
    }

    /**
     * 查看商品详情
     * */
    public function seeGoods(){
        if (!$this->request->param("id")) $this->error("id为空");
        $list=Merchantgoods::field("id,name,price,refer,images,status,type_data,cost_price,number,start_time,end_time")->find($this->request->param("id"));
        if(empty($list)) $this->error("商品不存在");
        if(!empty($list["images"])) $list["images"]=explode(",",$list["images"]);
        if(!empty($list["start_time"])) $list["start_time"]=date("Y-m-d H:i:s",$list["start_time"]);
        if(!empty($list["end_time"])) $list["end_time"]=date("Y-m-d H:i:s",$list["end_time"]);
        $this->success("成功",$list);
    }

    /**
     * 修改商品
     * */
    public function updateGoods(){
        $params = $this->request->param();
        $model=new Merchantgoods();
        if($this->request->param("card_type")){
            if (!$this->request->param("card_type_id")) $this->error("洗车类型不能为空");
            $type=Type::field("name,price")->where(["id"=>$this->request->param("card_type_id")])->find();
            if(empty($type)) $this->error("该洗车类型不存在");
            $data=[
                "merchant_id"=>$this->merchantUser["merchant_id"],
                "card_type_id"=>$params["card_type_id"],
                "name"=>$type["name"],
                "status"=>"1",
                "type_data"=>"1",
                "highest_price"=>$type["price"],
            ];
            if(isset($params["status"])){
                $data["status"]=$params["status"];
                if($params["status"]==1 && !isset($params["price"])){
                    $data["price"]=$type["price"];
                }
            }
            if(isset($params["price"])){
                $data["price"]=$params["price"];
            }
            if(isset($params["images"])){
                $data["images"]=$params["images"];
            }
            if($this->request->param("id")){
                $model->where(["id"=>$params["id"]])->update($data);
            }else{
                $list=$model->field("id")
                    ->where(["type_data"=>'1',"card_type_id"=>$params["card_type_id"],"merchant_id"=>$this->merchantUser["merchant_id"]])
                    ->find();
                if(!empty($list)){
                    $model->where(["id"=>$list["id"]])->update($data);
                }else{
                    /*$type=Type::field("price")->where(["id"=>$params["card_type_id"]])->find();
                    $data["price"]=$type["price"]??0;*/
                    $model->allowField(true)->save($data);
                }
            }
        }else{
            $data=[
                ['name', 'require', '名称不能为空'],
                ['price', 'require', '价格不能为空'],
                ['id', 'require', 'id不能为空'],
            ];
            if($this->request->param("type_data")==1){
                //次卡
                $data=array_merge($data,[
                    ['cost_price', 'require', '原价不能为空'],
                    ['number', 'require', '次数不能为空'],
                    ['start_time', 'require', '开始时间不能为空'],
                    ['end_time', 'require', '结束时间不能为空'],
                ]);
            }
            $validate = new \think\Validate($data);
            if (!$validate->check(input())) {
                $this->error('提交失败：' . $validate->getError());
            }
            $goods=$model->get($params["id"]);
            if(empty($goods)) $this->error("商品不存在");
            if($params["type_data"]==1){
                $params["start_time"]=strtotime($params["start_time"]);
                $params["end_time"]=strtotime($params["end_time"]);
                $params["card_type_id"]=0;
            }
            if($this->request->param("card_type_id")){
                unset($params["card_type_id"]);
            }
            $goods->allowField(true)->save($params);
        }
        $this->success("成功");
    }

    /**
     * 获取总平台洗车类型
     * */
    public function getMerchantCard(){
        $page = !$this->request->param('page') ? 1 : $this->request->param('page');//页
        $list=Type::field("id,name,price")->where(["switch"=>'1'])
            ->paginate(10, '', ['page' => $page, 'list_rows' => 10])
            ->each(function ($v){
                $goods=Merchantgoods::field("id,status,images,price,card_type_id")
                    ->where(["card_type_id"=>$v["id"],"merchant_id"=>$this->merchantUser["merchant_id"],"type_data"=>'1'])
                    ->find();
                $v["goods_status"]=false;
                if(!empty($goods)){
                    $v["goods_status"]=true;
                    $v["goods"]=[
                        "status"=>$goods["status"],
                        "id"=>$goods["id"],
                        "images"=>!empty($goods["images"])?explode(",",$goods["images"]):'',
                        "price"=>$goods["price"],
                        "card_type_id"=>$goods["card_type_id"],
                    ];
                }
            });
        $this->success("成功",$list);
    }

    /**
     * 删除商品
     * */
    public function delGoods(){
        if (!$this->request->param("id")) $this->error("id为空");
        $list=Merchantgoods::field("id")->find($this->request->param("id"));
        if(empty($list)) $this->error("商品不存在");
        $list->delete();
        $this->success("成功",$list);
    }

    /**
     * 上下架商品
     * */
    public function shelvesGoods(){
        if (!$this->request->param("id")) $this->error("id为空");
        $params=$this->request->param();
        if(!isset($params["status"])) $this->error("请选择状态");
        $list=Merchantgoods::field("id,name,price,refer,images,status")->find($this->request->param("id"));
        if(empty($list)) $this->error("商品不存在");
        $list->save(["status"=>$this->request->param("status")]);
        $this->success("成功");
    }
    /******************************** 店铺商品管理 end*****************************************************************************/


    /******************************** 店铺员工管理 start*****************************************************************************/
    /**
     * 岗位列表
     * */
    public function listPost(){
        $page = !$this->request->param('page') ? 1 : $this->request->param('page');//页
        $list=Merchantpost::field("id,name,scope")
            ->where(["merchant_id"=>$this->merchantUser["merchant_id"]])
            ->order("createtime","desc")
            ->paginate(10, '', ['page' => $page, 'list_rows' => 10]);
        $this->success("成功",$list);
    }
    /**
     * 添加岗位
     * */
    public function addPost(){
        $data=[
            ['name', 'require', '岗位名称不能为空'],
            ['scope', 'require', '职务范围不能为空'],
        ];
        $validate = new \think\Validate($data);
        if (!$validate->check(input())) {
            $this->error('提交失败：' . $validate->getError());
        }
        $params = $this->request->param();
        $params["merchant_id"]=$this->merchantUser["merchant_id"];
        $model=new Merchantpost();
        $model->allowField(true)->save($params);
        $this->success("成功");
    }
    /**
     * 修改岗位
     * */
    public function updatePost(){
        $data=[
            ['id', 'require', 'id不能为空不能为空'],
            ['name', 'require', '岗位名称不能为空'],
            ['scope', 'require', '职务范围不能为空'],
        ];
        $validate = new \think\Validate($data);
        if (!$validate->check(input())) {
            $this->error('提交失败：' . $validate->getError());
        }
        $params = $this->request->param();
        $model=new Merchantpost();
        $merchantpost=$model->get($params["id"]);
        if(empty($merchantpost)) $this->error("岗位不存在");
        $merchantpost->allowField(true)->save($params);
        $this->success("成功");
    }
    /**
     * 删除岗位
     * */
    public function delPost(){
        if (!$this->request->param("id")) $this->error("id为空");
        $list=Merchantpost::field("id")->find($this->request->param("id"));
        if(empty($list)) $this->error("岗位不存在");
        $list->delete();
        $this->success("成功");
    }

    /**
     * 查看岗位详情
     * */
    public function seePost(){
        if (!$this->request->param("id")) $this->error("id为空");
        $list=Merchantpost::field("id,name,scope")->find($this->request->param("id"));
        if(empty($list)) $this->error("岗位不存在");
        $this->success("成功",$list);
    }


    /**
     * 员工列表
     * */
    public function listUser(){
        $page = !$this->request->param('page') ? 1 : $this->request->param('page');//页
        $list=Merchantuser::field("id,name,avatar,mobile,status")
            ->with(["merchantpost"=>function($query){
                $query->withField('name');
            }])
            ->where(["merchantuser.merchant_id"=>$this->merchantUser["merchant_id"],"is_super"=>'0'])
            ->order("merchantuser.createtime","desc")
            ->paginate(10, '', ['page' => $page, 'list_rows' => 10]);
        $this->success("成功",$list);
    }
    /**
     * 新增员工
     * */
    public function addUser(){
        $data=[
            ['name', 'require', '员工姓名不能为空'],
            ['merchantpost_id', 'require', '岗位不能为空'],
            ['avatar', 'require', '员工照片不能为空'],
            ['mobile', 'require|regex:/^1\d{10}$/|unique:merchantuser', '手机号码（账号）不能为空|手机号码（账号）格式错误|手机号码（账号）已存在'],
            ['password', 'require|regex:\S{6,30}', '密码不能为空|密码长度必须在6-30位之间，不能包含空格'],
        ];
        $validate = new \think\Validate($data);
        if (!$validate->check(input())) {
            $this->error('提交失败：' . $validate->getError());
        }
        $params = $this->request->param();
        $model=new Merchantuser();
        /*$user=$model->where(["mobile"=>$params["mobile"]])->find();
        if(!empty($user)) $this->error("该手机号已存在账户");*/
        $params["merchant_id"]=$this->merchantUser["merchant_id"];
        //$params["username"]=$params["mobile"];
        $params['salt'] = Random::alnum();
        $params['password'] = md5(md5($params['password']) . $params['salt']);
        $model->allowField(true)->save($params);
        $this->success("成功");
    }
    /**
     * 修改员工
     * */
    public function updateUser(){
        $data=[
            ['id', 'require', 'id不能为空不能为空'],
            ['merchantpost_id', 'require', '岗位不能为空'],
            ['avatar', 'require', '员工照片不能为空'],
            ['mobile', 'require|regex:/^1\d{10}$/|unique:merchantuser,mobile,'.$this->request->param("id"), '手机号码（账号）不能为空|手机号码（账号）格式错误|手机号码（账号）已存在'],
        ];
        $validate = new \think\Validate($data);
        if (!$validate->check(input())) {
            $this->error('提交失败：' . $validate->getError());
        }
        $params = $this->request->param();
        if (isset($params['password'])) {
            if (!Validate::is($params['password'], '\S{6,30}')) {
                $this->error("密码格式错误");
            }
            $params['salt'] = Random::alnum();
            $params['password'] = md5(md5($params['password']) . $params['salt']);
            if(empty($params['password'])){
                unset($params['password'], $params['salt']);
            }
        }
        $model=new Merchantuser();
        $user=$model->get($params["id"]);
        if(empty($user)) $this->error("员工不存在");
        $user->allowField(true)->save($params);
        $this->success("成功");
    }
    /**
     * 删除员工
     * */
    public function delUser(){
        if (!$this->request->param("id")) $this->error("id为空");
        $list=Merchantuser::field("id")->find($this->request->param("id"));
        if(empty($list)) $this->error("员工不存在");
        $list->delete();
        $this->success("成功");
    }

    /**
     * 查看员工详情
     * */
    public function seeUser(){
        if (!$this->request->param("id")) $this->error("id为空");
        $list=Merchantuser::field("id,name,avatar,mobile,status,createtime,merchantpost_id")
            ->with([
                "merchantpost"=>function($query){
                    $query->withField('name');
                }
            ])
            ->where(["merchantuser.id"=>$this->request->param("id")])
            ->find();
        if(empty($list)) $this->error("员工不存在");
        $this->success("成功",$list);
    }
    /**
     * 修改员工状态
     * */
    public function statusUser(){
        if (!$this->request->param("id")) $this->error("id为空");
        if (!in_array($this->request->param("status"),[1,2])) $this->error("状态错误");
        $list=Merchantuser::field("id,name,avatar,mobile,status,createtime")->find($this->request->param("id"));
        if(empty($list)) $this->error("员工不存在");
        $list->save(["status"=>$this->request->param("status")]);
        $this->success("成功",$list);

    }
    /******************************** 店铺员工管理 end*****************************************************************************/


    /**
     * 核销
     * */
    public function writeOff(){
        if (!$this->request->param("mycardlog_id")) $this->error("洗车类型为空");
        $res=$this->getLog($this->request->param("mycardlog_id"));
        if(!$res) return $res;
        $log=Mycardlog::where(["id"=>$this->request->param("mycardlog_id")])->find();
        if(empty($log)) $this->error("没有可用洗车");
        if($log["residue"]<=0) $this->error("次数已用完");
        if($res["type_data"]!=2){
            $goods=Merchantgoods::field("price,status")->where(["card_type_id"=>$log["card_type_id"],"type_data"=>'1',"merchant_id"=>$this->merchant["id"]])->find();
            if(empty($goods) || $goods["status"]!=1) $this->error("店铺未加入该会员价");
        }
        Db::startTrans();
        try {
            $data=[
                "mycard_id"=>$res["id"],
                "mycardlog_id"=>$log["id"],
                "image"=>$this->merchant["door_image"],//门头照
                "merchant_name"=>$this->merchant["name"],
                "merchant_address"=>$this->merchant["address"],
                "merchant_id"=>$this->merchant["id"],
                "merchantuser_id"=>$this->merchantUser["id"],
                "name"=>$res["name"],
                "card_type_name"=>$log["card_type_name"],
                "createtime"=>time(),
                "member_id"=>$res["member_id"],
                "price"=>($res["type_data"]==1 || $res["type_data"]==3) && !empty($goods)?$goods["price"]:0,//$log["price"],//7-18新增核销价格
                //"member_nickname"=>$res["nickname"],
            ];
            $id=Washlog::insertGetId($data);
            $log->save(["residue"=>$log["residue"]-1]);
            $model=new Order();
            $data=Washlog::where(["id"=>$id])->find();
            $merchant_money=$res["type_data"]!=2?$goods["price"]:$log["price"];
            if(($res["type_data"]==1 || $res["type_data"]==3) && !empty($goods)){
                $merchant_money=$model->writeCalculateCommission($log,$data,$this->merchant["classify"],$this->merchant["id"],$goods["price"]);
            }
            //发送消息
            \app\common\model\Message::create([
                "title"=>"核销成功",
                "member_ids"=>$data["member_id"],
                "info"=>"您已在".$this->merchant["name"]." 店铺 ".date("Y-m-d H:i:s")." 核销  ".$data["name"]."成功， 祝你行程愉快。",
                "createtime"=>time(),
            ]);
            //添加核销记录 2023-7-11 start
            $write_data=[
                "mycard_id"=>$res["id"],
                "mycardlog_id"=>$log["id"],
                "card_type_name"=>$log["card_type_name"],
                "card_type_id"=>$log["card_type_id"],
                "createtime"=>time(),
                "merchant_id"=>$this->merchant["id"],
                "merchantuser_id"=>$this->merchantUser["id"],
                "member_id"=>$res["member_id"],
                "price"=>$merchant_money,
                "type_data"=>$res["type_data"],
            ];
            $member=Member::field("nickname,wxopenid")->where(["id"=>$res["member_id"]])->find();
            $write_data["member_nickname"]=$member["nickname"];
            Write::create($write_data);
            //添加核销记录 2023-7-11  end
            //新增 给用户发送模板消息 start
            //$member["wxopenid"]="onyHr51gVC3cRH8BqCBjp8Eb8JR8";
            if(!empty($member["wxopenid"])){
                $index=new Index();
                $template_id="wrFip7VtZEbIljHObOGXXq0-VkOC-Ze1VKnqZm0P_JE";
                $length=strlen($this->merchant["address"]);
                if($length>20){
                    $this->merchant["address"]=mb_substr($this->merchant["address"],0,16,"utf-8")."...";
                }
                $send_data=[
                    "thing7"=>[
                        "value"=>$data["name"]
                    ],//核销项目
                    "thing6"=>[
                        "value"=>$this->merchant["name"]
                    ],//核销门店
                    "thing5"=>[
                        "value"=>$this->merchant["address"]
                    ],//地址
                    "time3"=>[
                        "value"=>date("Y-m-d H:i:s",time())
                    ],//核销时间
                ];
                $parkUrl=$this->merchant["parkUrl"];
                if(!empty($this->merchant["parkUrl"])){
                    $send_data["thing7"]=[
                        "value"=>"（点击查看详情领取停车券）"];
                }
               /* $name_length=strlen($this->merchant["name"]);
                if($name_length>20){
                    $this->merchant["name"]=mb_substr($this->merchant["name"],0,16,"utf-8")."...";
                }*/
                $index->send_temp($template_id,$member["wxopenid"],$send_data,"",$parkUrl);
            }
            //新增 给用户发送模板消息 end
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success("核销成功");
    }

    private function getLog($mycardlog_id=0){
        if(!empty($mycardlog_id)){
            $log=Mycardlog::where(["id"=>$mycardlog_id])->find();
            $mycard=Mycard::get(["id"=>$log["mycard_id"]]);
        }else{
            if (!$this->request->param("id") && !$this->request->param("write_number")) $this->error("id为空");
            //类型:1=卡包,2=店铺洗车卡,3=实体卡
            $where=["id"=>$this->request->param("id")];
            if($this->request->param("write_number")){
                $where=["write_number"=>$this->request->param("write_number"),"status"=>'0'];
            }
            $mycard=Mycard::get($where);
        }
        if(empty($mycard)) $this->error("卡券不存在");
        if($mycard["status"]==1) $this->error("已过期");
        if($mycard["status"]==2) $this->error("已完成");
        if($mycard["type_data"]==2 && $mycard["merchant_id"]!=$this->merchant["id"]) $this->error("该洗车卡不能在该门店使用");
        return $mycard;
    }

    /**
     * 获取可核销的洗车类型
     * */
    public function getCardType(){
        $res=$this->getLog();
        if(!$res) return $res;
        $where="1=1";
        if($res["type_data"]!=2){
            $where="residue >0  and price<=highest_price and card_type_id IN (SELECT card_type_id FROM tx_merchant_goods WHERE STATUS='1' and merchant_id=".$this->merchant["id"]
                .")";
        }
        $log=Mycardlog::field("id,card_type_name,residue")
            ->where(["mycard_id"=>$res["id"]])
            ->where($where)
            ->select();
        if(empty($log)) $this->error("没有可核销的洗车类型");
        $this->success("成功",["log"=>$log,"id"=>$res["id"]]);
    }

    /**
     * 核销普通商品
     * */
    public function writeOffGoods(){
        if (!$this->request->param("id") && !$this->request->param("write_number")) $this->error("id为空");
        $where=["id"=>$this->request->param("id"),"status"=>'3'];
        if($this->request->param("write_number")){
            $where=["write_number"=>$this->request->param("write_number"),"status"=>'3'];
        }
        $order=Order::get($where);
        if(empty($order)) $this->error("订单不存在或已核销");
        if($order["merchant_id"]!=$this->merchant["id"]) $this->error("该商品不能在该门店使用");
        $member_id=$order["member_id"];
        Db::startTrans();
        try {
            $order->save([
                "status"=>'1',
                "write_time"=>time(),
            ]);
            //发送消息
            \app\common\model\Message::create([
                "title"=>"核销成功",
                "member_ids"=>$order["member_id"],
                "info"=>"您已在".$this->merchant["name"]." 店铺 ".date("Y-m-d H:i:s")." 核销  ".$order["name"]."成功， 祝你行程愉快。",
                "createtime"=>time(),
            ]);
            //添加核销记录 2023-7-11 start
            $write_data=[
                "mycard_id"=>0,
                "mycardlog_id"=>0,
                "card_type_name"=>$order["name"],
                "card_type_id"=>$order["card_kabaw_id"],
                "createtime"=>time(),
                "merchant_id"=>$this->merchant["id"],
                "merchantuser_id"=>$this->merchantUser["id"],
                "member_id"=>$member_id,
                "price"=>$order["merchantuser_money"],
                "type_data"=>'0',
            ];
            $member=Member::field("nickname,wxopenid")->where(["id"=>$member_id])->find();
            $write_data["member_nickname"]=$member["nickname"];
            Write::create($write_data);
            //添加核销记录 2023-7-11  end
            //新增 给用户发送模板消息 start
            //$member["wxopenid"]="onyHr51gVC3cRH8BqCBjp8Eb8JR8";
            if(!empty($member["wxopenid"])){
                $index=new Index();
                $length=strlen($this->merchant["address"]);
                if($length>20){
                    $this->merchant["address"]=mb_substr($this->merchant["address"],0,16,"utf-8")."...";
                }
                $index->send_temp("wrFip7VtZEbIljHObOGXXq0-VkOC-Ze1VKnqZm0P_JE",$member["wxopenid"],
                    [
                        "thing7"=>[
                            "value"=>$order["name"]
                        ],//核销项目
                        "thing6"=>[
                            "value"=>$this->merchant["name"]
                        ],//核销门店
                        "thing5"=>[
                            "value"=>$this->merchant["address"]
                        ],//地址
                        "time3"=>[
                            "value"=>date("Y-m-d H:i:s",time())
                        ],//核销时间
                    ],"my_pages/carWashRecord/carWashRecord");
            }
            //新增 给用户发送模板消息 end
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success("核销成功");
    }

    /**
     * 评论列表
     * */
    public function washlogList(){
        $page = !$this->request->param('page') ? 1 : $this->request->param('page');//页
        $centre=Washlog::field("count(id) value")
            ->where(["status"=>'1',"merchant_id"=>$this->merchant["id"]])
            ->where("score <=4 and score >=3")
            ->buildSql();//中
        $differ=Washlog::field("count(id) value")
            ->where(["status"=>'1',"merchant_id"=>$this->merchant["id"]])
            ->where("score < 3")
            ->buildSql();//差
        $list["score"]=Washlog::field("count(id) value")
        ->where(["status"=>'1',"merchant_id"=>$this->merchant["id"]])
            ->where("score >= 5")
            ->union([$centre,$differ],true)
            ->select();//已对接
        $list["data"]=Washlog::field("id,anonymous,name,card_type_name,image,from_unixtime(evaluate_time, '%Y-%m-%d %H:%i:%s') evaluate_time,
        evaluate_images,evaluate,score")
            ->with(["member"=>function($query){
                $query->withField('id,nickname');
            }])->where(["washlog.status"=>"1","washlog.merchant_id"=>$this->merchant["id"]])
            ->order("washlog.createtime","desc")
            ->paginate(10, '', ['page' => $page, 'list_rows' => 10])
            ->each(function ($v){
                if($v["anonymous"]==1 || empty($v["member"]["nickname"])) $v["member"]["nickname"]="匿名用户";
                if(!empty($v["evaluate_images"])) $v["evaluate_images"]=explode(",",$v["evaluate_images"]);
            });
        $this->success("成功",$list);
    }

    /**
     * 统计
     * */
    public function census(){
        //今日订单
        $where=["merchant_id"=>$this->merchant["id"]];
        /*if($this->merchant["is_trila"]==1){
            //飞狗平台
            $where=["merchantuser_id"=>$this->auth->id];
        }*/
        $list["today_order"]=Order::where($where)
            ->whereIn("status",['1','3'])
            ->whereTime("createtime","today")->count();
        //今日营业额
        $list["today_turnover"]=Order::where($where)
            ->whereIn("type_data",['0','2'])
            ->whereIn("status",['1','3'])
            ->whereTime("createtime","today")->sum("merchantuser_money");
        //今日收益
        $list["today_income"]=Washlog::where($where)->whereTime("createtime","today")
            ->sum("merchantuser_money");
        $list["today_income"]=bcadd($list["today_turnover"], $list["today_income"],2);
        //累计用户
        $order_num=Order::where($where)
            ->where("merchant_id not in (select merchant_id from tx_washlog)")
            ->count("DISTINCT member_id");
        $washlog_num=Washlog::where($where)
            ->where("merchant_id not in (select merchant_id from tx_order)")
            ->count("DISTINCT member_id");
        $list["member_num"]=$order_num+$washlog_num;
        $access_num=Merchantvisit::field("COUNT(DISTINCT DATE_FORMAT(FROM_UNIXTIME(createtime),'%Y-%m-%d')) num")
            ->where($where)
            ->whereTime("createtime","today")
            ->find();//今日访问数
        $list["access_num"]=$access_num["num"];
        $list["today_promotion"]=Member::where($where)->whereTime("merchantbind_time","today")->count();//今日推广数
        //今日新增用户
        $order_num=Order::where($where)
            ->whereTime("createtime","today")
            ->where("merchant_id not in (select merchant_id from tx_washlog) and merchant_id not in(select id from tx_order where createtime < ".time().")")
            ->count("DISTINCT member_id");
        $washlog_num=Washlog::where($where)
            ->where("merchant_id not in (select merchant_id from tx_order) and merchant_id not in(select id from tx_washlog where createtime < ".time().")")
            ->whereTime("createtime","today")->count("DISTINCT member_id");
        $list["today_member"]=$order_num+$washlog_num;
        $this->success("成功",$list);
    }

    /**
     * 订单管理
     * */
    public function orderList(){
        $page = !$this->request->param('page') ? 1 : $this->request->param('page');//页
        $list=Order::field("id,order_no,name,price,from_unixtime(createtime, '%Y-%m-%d %H:%i:%s') createtime")
            ->where(["merchant_id"=>$this->merchant["id"]]);
        if($this->request->param("day")){
            $day=$this->request->param("day");
            $day_field="today";
            if($day==2) $day_field="week";
            if($day==3) $day_field="month";
            if($day==4) $day_field="year";
            $list=$list->whereTime("createtime",$day_field);
        }else{
            if($this->request->param("start_time")){
                $list=$list->whereTime('createtime', 'between', [strtotime($this->request->param("start_time")."00:00:00"),strtotime($this->request->param("end_time")."23:59:59")]);
            }
        }
        $list=$list->whereIn("status",['1','3'])
            ->order("createtime","desc")->paginate(10, '', ['page' => $page, 'list_rows' => 10]);
        $this->success("成功",$list);
    }


    /**
     * 数据趋势
     * */
    public function orderChart(){
        $type = !$this->request->param('type') ? 0 : $this->request->param('type');//类型 0近30天 1本月 2本季度 3本年
        $list=Order::where(["merchant_id"=>$this->merchant["id"]]);
        if($type==0) $list=$list->field("count(1) num,from_unixtime(createtime, '%Y-%m-%d') title")->where("DATE_SUB(CURDATE(), INTERVAL 30 DAY) <= DATE_FORMAT(FROM_UNIXTIME(createtime), '%Y-%m-%d')");
        if($type==1) $list=$list->field("count(1) num,from_unixtime(createtime, '%Y-%m-%d') title")->whereTime("createtime","month");
        if($type==3) $list=$list->field("count(1) num,from_unixtime(createtime, '%m') title")->whereTime("createtime","year");
        if($type==2) $list=$list->field("count(1) num,from_unixtime(createtime, '%Y-%m-%d') title")->where("QUARTER(FROM_UNIXTIME(createtime, '%Y-%m-%d'))=QUARTER(now())");
        $list=$list->whereIn("status",['1','3'])->order("title")
            ->group("title")->buildSql();
        $washlog_num=Washlog::where(["merchant_id"=>$this->merchant["id"]]);
        if($type==0) $washlog_num=$washlog_num->field("count(1) num,from_unixtime(createtime, '%Y-%m-%d') title")->where("DATE_SUB(CURDATE(), INTERVAL 30 DAY) <= DATE_FORMAT(FROM_UNIXTIME(createtime), '%Y-%m-%d')");
        if($type==1) $washlog_num=$washlog_num->field("count(1) num,from_unixtime(createtime, '%Y-%m-%d') title")->whereTime("createtime","month");
        if($type==3) $washlog_num=$washlog_num->field("count(1) num,from_unixtime(createtime, '%m') title")->whereTime("createtime","year");
        if($type==2) $washlog_num=$washlog_num->field("count(1) num,from_unixtime(createtime, '%Y-%m-%d') title")->where("QUARTER(FROM_UNIXTIME(createtime, '%Y-%m-%d'))=QUARTER(now())");
        $washlog_num=$washlog_num->order("title")->group("title")
            ->union($list,true)
            ->order("title")->fetchSql()->select();
        $sql="select SUM(num) num,title from(".$washlog_num.") order_table GROUP BY title ";
        $data["cart"]=Db::query($sql);
        $sql="select SUM(num) num from(".$washlog_num.") order_table";
        $num=Db::query($sql);
        $data["num"]=$num[0]["num"];
        /*$list=Order::field("count(1) num,from_unixtime(createtime, '%Y-%m-%d') title")
            ->where(["merchant_id"=>$this->merchant["id"]]);
        if($type==0) $list=$list->where("DATE_SUB(CURDATE(), INTERVAL 30 DAY) <= DATE_FORMAT(FROM_UNIXTIME(createtime), '%Y-%m-%d')");
        if($type==1) $list=$list->whereTime("createtime","month");
        if($type==3) $list=$list->whereTime("createtime","year");
        if($type==2) $list=$list->where("QUARTER(FROM_UNIXTIME(createtime, '%Y-%m-%d'))=QUARTER(now())");
        $data["cart"]=Order::field("count(1) num,from_unixtime(createtime, '%Y-%m-%d') title")
            ->where(["merchant_id"=>$this->merchant["id"]])->whereIn("status",['1','3'])->order("title")
            ->group("title")->select();
        $count=0;
        foreach ($list as $v){
            $count+=$v["num"];
        }
        $data["num"]=$count;*/
        $this->success("成功",$data);
    }
    /**
     * 获取推广码
     * */
    public function getPromotionCode(){
        $code=[
            "promotion_code"=>$this->merchant["promotion_code"],
            "promotion_url"=>$this->merchant["promotion_url"],
        ];
        if(empty($user["promotion_code"]) || empty($user["promotion_url"])){
            $mycardModel = new Merchant();
            $code=$mycardModel->getPromotionCode($this->merchant["id"]);//生成二维码
        }
        $this->success("成功",$code);
    }

    /**
     * 核销列表
     * */
    public function writeList(){
        $page = !$this->request->param('page') ? 1 : $this->request->param('page');//页
        $list=Write::field("id,card_type_name,member_nickname,price,type_data,from_unixtime(createtime, '%Y-%m-%d %H:%i:%s') createtime")
            ->where(["merchant_id"=>$this->merchant["id"]]);
        if($this->request->param("day")){
            $day=$this->request->param("day");
            $day_field="today";
            if($day==2) $day_field="month";
            $list=$list->whereTime("createtime",$day_field);
        }else{
            if($this->request->param("start_time")){
                $list=$list->whereTime('createtime', 'between', [strtotime($this->request->param("start_time")."00:00:00"),strtotime($this->request->param("end_time")."23:59:59")]);
            }
        }
        $model=new Member();
        $list=$list->order("createtime","desc")
            ->paginate(10, '', ['page' => $page, 'list_rows' => 10])
            ->each(function ($v) use($model){
                $v["member_nickname"]=$model->emoji_decode($v["member_nickname"]);
            })
        ;
        $this->success("成功",$list);
    }


}
